import signal
import sys
import os
from concurrent import futures
import logging
import grpc
from loguru import logger

BASE_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, BASE_DIR)

from user_srv.proto import user_pb2, user_pb2_grpc
from user_srv.handler.user import UserServicer


@logger.catch
def my_function(x, y, z):
    return 1 / (x + y + z)


def on_exit(signo, frame):
    logger.info("进程中断")
    sys.exit(0)


def server():
    # logger.add("logs/user_srv_{time}.log")
    logger.add("logs/user_srv_x.log", rotation="12:00")
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    user_pb2_grpc.add_UserServicer_to_server(UserServicer(), server)
    server.add_insecure_port('[::]:50051')
    # 主进程退出监听
    """
        windows下支持的信号是有限的
              SIGINT        ctrl+c中断
              SIGTERM        kill发出的软件中止
    """
    signal.signal(signal.SIGINT, on_exit)
    signal.signal(signal.SIGTERM, on_exit)
    logger.info(f"启动服务：127.0.0.1:50051")
    server.start()
    server.wait_for_termination()


if __name__ == '__main__':
    # logger.debug("调试信息")
    # logger.info("普通信息")
    # logger.warning("警告信息")
    # logger.error("错误信息")
    # logger.critical("严重错误信息")
    # logging.basicConfig()
    server()